package com.chookss.home.audit.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.document.DownloadService;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.mine.entity.MineInfoEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.filePicker.util.FileUtils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.InitDialog;
import com.chookss.view.listener.ShareDialogListener;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserInfoDocunmentListAdapter extends BaseQuickAdapter<MineInfoEntity.DatabaseBean, BaseViewHolderEx> {
    private Context context;
    private String tag;//记录来源
    private boolean isEdit=false;//false默认不可以编辑删除true可以编辑
    public UserInfoDocunmentListAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<MineInfoEntity.DatabaseBean> data,boolean isEdit, String tag) {
        super(layoutResId, data);
        this.context=context;
        this.isEdit=isEdit;
        this.tag=tag;
    }
    public void setEdit(boolean edit){
        this.isEdit=edit;
    }
    @Override
    protected void convert(BaseViewHolderEx helper, MineInfoEntity.DatabaseBean entity) {
        ImageView ivIconType = helper.getView(R.id.iv_item_file_select_left);
        TextView tvItemTitle = helper.getView(R.id.tv_item_file_list);
        LinearLayout llMiddle = helper.getView(R.id.llMiddle);
        TextView tvItemDate = helper.getView(R.id.tv_item_file_list_desc);
        RelativeLayout rlStatus = helper.getView(R.id.rlStatus);
        ProgressBar progressBar = helper.getView(R.id.progressBar);
        if (entity.getProgress() == 0 || entity.getProgress() == 100) {
            progressBar.setVisibility(View.GONE);
        } else {
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(entity.getProgress());
        }
        if(isEdit){
            rlStatus.setVisibility(View.VISIBLE);
        }else{
            LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) llMiddle.getLayoutParams();
            params.setMargins(Utils.dip2px(context,12),0,Utils.dip2px(context,12),0);
            llMiddle.setLayoutParams(params);
            rlStatus.setVisibility(View.GONE);
        }
//            String fileType = entity.getFileType();//文件类型1--word 2 --excel 3--PPT  4pdf.
        tvItemTitle.setText(entity.getDataTitle());
        tvItemDate.setText(String.format(context.getString(R.string.file_desc),entity.getUploadTime(), Utils.changeKM(entity.getDataSize())));
        rlStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new InitDialog(context,
                        "提示", "确定要删除么？", "确定", true,
                        new ShareDialogListener() {
                            @Override
                            public void onClick() {
                                Map<String, String> map = new HashMap<>();
                                map.put("position", helper.getItemPosition() + "");
                                map.put("deleteDocunment", "deleteDocunment");
                                EventBus.getDefault().post(new MyEvent(map));
                            }
                        }).show();

            }
        });
        String fileNameExtension = FileUtils.getExtension(entity.getDataTitle()).toLowerCase();
        switch (fileNameExtension) {
            case "doc":
            case "docx":
                ivIconType.setImageResource(R.drawable.icon_w_80);
                break;
            case "pdf":
                ivIconType.setImageResource(R.drawable.icon_pdf_80);
                break;
            case "ppt":
            case "pptx":
                ivIconType.setImageResource(R.drawable.icon_p_80);
                break;
            case "xls":
            case "xlsx":
                ivIconType.setImageResource(R.drawable.icon_x_80);
                break;
            case "ext":
            default:
                ivIconType.setImageResource(R.drawable.icon_mr_80);
                break;
        }
        helper.getItemView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Utils.isNull(entity.getDataCode())){
//                    if(!MyApp.mIsInitTBSSuccess){
//                        //腾讯文件浏览功能失败
//                        FileOpen.openFile(context,entity.getDataPath());
//                    } else if(!MyApp.docunmentOpen) {
//                        Intent intent = new Intent(context, DocumentLocalPreviewActivity.class);
//                        intent.putExtra("fileUrl", entity.getDataPath());
//                        intent.putExtra("fileName", entity.getDataTitle());
//                        context.startActivity(intent);
//                    }
                }else{
                    if(!isEdit){
                        requestSTORAGE(entity, tvItemTitle.getText().toString(), helper.getItemPosition());
                    }

                }
            }
        });
    }
    private void requestSTORAGE(MineInfoEntity.DatabaseBean entity, String retitle, int rePosition) {
        XXPermissions.with(context)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            getDocunmentDetail(entity, retitle, rePosition);
                        } else {
                            MyToast.show("存储未被授权，请先去权限设置里面授权");
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(context, denied, quick);
                    }
                });
    }

    private void getDocunmentDetail(MineInfoEntity.DatabaseBean entity, String docTitle, int docPosition) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", entity.getDataCode());
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity newData) {
                if (newData != null) {
                    openFile(newData, docTitle, docPosition,entity.isError());
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void openFile(DocunmentEntity entity, String title, int position,boolean isError) {
        if (!Utils.isNull(entity.getDataUrl())) {
            String url, name, fileUrl, urls;
            url = entity.getDataUrl();
            urls = url.split("\\?")[0];
            fileUrl = urls.substring(urls.lastIndexOf("/") + 1, urls.length());
            if (MyApp.downloadFiles.contains(title)||!MyApp.mIsInitTBSSuccess||isError) {
                if (!MyApp.docunmentOpen) {
                    Intent intent = new Intent(context, DocumentPreviewActivity.class);
                    intent.putExtra("fileUrl", fileUrl);
                    intent.putExtra("fileName", title);
                    intent.putExtra("dataCode", entity.getDataCode());
                    intent.putExtra("secret", true);
                    context.startActivity(intent);
                }
            } else {
//                    downTask(url, title, entity, position);
                entity.setProgress(1);
                notifyItemChanged(position);
                Intent intent = new Intent(context, DownloadService.class);
                intent.putExtra("fileUrl", fileUrl);
                intent.putExtra("fileName", title);
                intent.putExtra("url", url);
                intent.putExtra("dataCode", entity.getDataCode());
                intent.putExtra("position", position);
                intent.putExtra("tag", tag);
                context.startService(intent);
            }

        }
    }
}
